import customerApi from '../../utils/customerApi' // 引入api接口管理文件
import {
  throttle
} from '../../utils/util'
import {
  upload,
  imgUrl
} from '../../config/config'
const app = getApp()
const websocket = require('../../utils/socket')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customerChoose: {},
    talkList: [],
    messageText: '',
    imgUrl: imgUrl,
    toView: '',
    beforeTime: null,
    afterTime: null,
    totalLimit: 0,
    isFullSucreen: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      beforeTime: new Date().getTime(),
      customerChoose: app.globalData.customerChoose,
      isFullSucreen: app.globalData.isFullSucreen
    }, () => {
      this.getList()
    })
    const that = this
    websocket.ws_connect({}, (res) => {
      let data = JSON.parse(res)
      console.log('WebSocket customerService ===>', res);
      if (data.msg) {
        that.setData({
          afterTime: new Date().getTime() - 10000,
          beforeTime: null,
          toView: ''
        }, () => {
          that.getList()
        })
      }
    })

    // wx.onKeyboardHeightChange(res => {
    //   console.log(res.height, 'onKeyboardHeightChange===========')
    //   if (res.height * 1 === 0 && this.data.messageText !== '') {
    //     this.sendText()
    //   }
    // })
  },

  sendText() {
    if (this.data.messageText === '') {
      return
    }
    let afterTime = new Date().getTime()
    customerApi.conversationSendTextMessage({
      data: {
        friend_uid: this.data.customerChoose.friend_uid,
        friend_type: this.data.customerChoose.friend_type,
        message: {
          "message_text": this.data.messageText
        }
      },
      success: res => {
        if (res.code * 1 === 0) {
          this.setData({
            messageText: '',
            beforeTime: null,
            afterTime: afterTime - 10000,
            toView: ''
          }, () => {
            this.getList()
          })
        }
      }
    })
  },
  more() {
    this.setData({
      beforeTime: this.data.talkList[0].send_time,
      afterTime: null,
      toView: false
    }, () => {
      this.getList()
    })
  },

  getList() {
    const that = this
    customerApi.conversationReceiveMessage({
      data: {
        conversation_id: this.data.customerChoose.conversation_id,
        before: this.data.beforeTime,
        after: this.data.afterTime,
        limit: 30,
        update_new_messages_count: true
      },
      success: res => {
        if (res.code * 1 === 0) {
          // 转客服判断
          for (let i = 0; i < res.data.length; i ++) {
            if (that.data.afterTime && res.data[i].type === 'INFO' && res.data[i].action_tag === 'transfer_conversation') {
              customerApi.getTransferConversationInfo({
                data: {
                  old_conversation_id: res.data[i].conversation_id,
                  transfer_conversation_id: res.data[i].action_tag_value,
                  message_id: res.data[i].message_id
                },
                success: tranRes => {
                  console.log(tranRes, 'tranRes==========')
                  if (tranRes.code * 1 === 0) {
                    app.globalData.customerChoose = tranRes.data
                    that.onLoad()
                  }
                }
              })
              break
            }
          }

          let data = []
          let temp = {}
          let result = []
          if (this.data.afterTime) {
            data = [...this.data.talkList, ...res.data.reverse()]
          }
          if (this.data.beforeTime) {
            data = [...res.data.reverse(), ...this.data.talkList]
          }
          data.map(function (item, index) {
            if (!temp[item.message_id]) {
              result.push(item);
              temp[item.message_id] = true
            }
          })
          
          console.log('temp: ====', temp);
          this.setData({
            talkList: result,
            toView: this.data.toView === '' ? 'data' + data[data.length - 1]['message_id'] : null,
            totalLimit: res.data.length
          })
        }
      }
    })
  },

  textInput(e) {
    this.setData({
      messageText: e.detail.value
    })
  },

  showPic() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        wx.uploadFile({
          url: upload, //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          success(res) {
            const data = JSON.parse(res.data)
            if (data.code * 1 === 0) {
              let url = data.data.url
              that.sendImageMessageUrl(url)
            }
            //do something
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  sendImageMessageUrl(url) {
    const that = this
    customerApi.sendImageMessageUrl({
      data: {
        friend_uid: that.data.customerChoose.friend_uid,
        friend_type: that.data.customerChoose.friend_type,
        conversation_id: that.data.customerChoose.conversation_id,
        image_url: url
      },
      success: res => {
        that.setData({
          afterTime: new Date().getTime() - 10000,
          beforeTime: null,
          toView: ''
        }, () => {
          that.getList()
        })
      }
    })
  },

  moveTo(e) {
    let productId = e.currentTarget.dataset.productid
    let uid = e.currentTarget.dataset.uid
    wx.setStorageSync('customerUid', uid)
    throttle(function (e) {
      wx.navigateTo({
        url: `../detail/detail?productId=${productId}&type=2`
      })
    }, 2000)
  },

  showImg (e) {
    let url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url]
    })
  }
})